package com.xy.kafka.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
public class KafkaProducerService {

    private final KafkaTemplate<String, String> kafkaTemplate;

    @Autowired
    public KafkaProducerService(KafkaTemplate<String, String> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    /**
     * 发送消息到指定主题
     * @param topic 主题名称
     * @param message 消息内容
     */
    public void sendMessage(String topic, String message) {
        try {
            kafkaTemplate.send(topic, message);
            System.out.println("已发送消息到主题: " + topic + "，内容: " + message);
        } catch (Exception e) {
            System.out.println("错误: 发送消息到主题 [" + topic + "] 失败。错误信息: " + e.getMessage());
        }
    }

    /**
     * 发送消息到默认主题
     * @param message 消息内容
     */
    public void sendMessage(String message) {
        // 使用默认主题 tc-topic
        String defaultTopic = "tc-topic";
        sendMessage(defaultTopic, message);
    }
}